package io.gitee.cloudladder.obsidian.swagger2.plugin;

import io.gitee.cloudladder.obsidian.swagger2.annotation.ApiErrorCode;
import io.gitee.cloudladder.obsidian.swagger2.annotation.ApiErrorCodes;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import springfox.documentation.service.ObjectVendorExtension;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.Arrays;
import java.util.Objects;

@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public class ApiErrorCodeBuilderPlugin implements OperationBuilderPlugin {

    @Override
    public void apply(OperationContext operationContext) {
        ApiErrorCodes apiErrorCodes = operationContext.getHandlerMethod().getMethodAnnotation(ApiErrorCodes.class);
        ObjectVendorExtension objectVendorExtension = new ObjectVendorExtension("x-error-code");

        if (Objects.nonNull(apiErrorCodes)) {
            ApiErrorCode[] codes = apiErrorCodes.value();
            for (ApiErrorCode code : codes) {
                objectVendorExtension.addProperty(new StringVendorExtension(String.valueOf(code.code()), code.message()));
            }
            operationContext.operationBuilder().extensions(Arrays.asList(objectVendorExtension));
        } else {
            ApiErrorCode apiErrorCode = operationContext.getHandlerMethod().getMethodAnnotation(ApiErrorCode.class);
            if (Objects.nonNull(apiErrorCode)) {
                objectVendorExtension.addProperty(new StringVendorExtension(String.valueOf(apiErrorCode.code()), apiErrorCode.message()));
                operationContext.operationBuilder().extensions(Arrays.asList(objectVendorExtension));
            }
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

}
